import * as XLSX from 'xlsx';
import fs from 'fs'

class ExcelTools {
    readonly excelPath: string = './excel';
    readonly excelJson: string = './excel/json/';
    readonly excelTs: string = './excel/ts/'

    async parse() {
        if (fs.existsSync(this.excelJson))
            fs.rmSync(this.excelJson, { recursive: true })
        fs.mkdirSync(this.excelJson);
        
        if (fs.existsSync(this.excelTs))
            fs.rmSync(this.excelTs, { recursive: true })
        fs.mkdirSync(this.excelTs);

        const files = await this.readExcel(this.excelPath);
        console.log('*********readExcel success:' + files)
        for (let i = 0; i < files.length; i++) {
            const path = this.excelPath + '/' + files[i]
            const { workbook, sheetNames } = this.parseExcel(path);
            if (workbook && sheetNames) {
                for (let j = 0; j < sheetNames.length; j++) {
                    const sheetName = sheetNames[j];
                    const sheet = workbook.Sheets[sheetName];
                    let data: any[] = XLSX.utils.sheet_to_json(sheet);
                    await this.saveToJson(this.excelJson, sheetName, data);
                    console.log('*********savetojson success:' + sheetName)
                    await this.saveToTs(this.excelTs, sheetName, data);
                    console.log('*********saveToTs success:' + sheetName)
                }
            }
        }
    }

    readExcel(dir: string) {
        return new Promise<string[]>((resolve, reject) => {
            fs.readdir(dir, (err, files) => {
                if (err) {
                    reject(err)
                }
                else {
                    files = files.filter(a => a.includes('.xlsx') && !a.startsWith('~$'))
                    resolve(files)
                }
            })
        })
    }

    parseExcel(path: string) {
        let workbook = null, sheetNames = null
        try {
            workbook = XLSX.readFile(path);
            sheetNames = workbook.SheetNames;
        }
        catch (error) {
            console.error('Error parsing the Excel file:', error);
        }
        finally {
            return { workbook, sheetNames }
        }
    }

    saveToJson(path: string, sheetName: string, data: any[]) {
        return new Promise((resolve, reject) => {
            try {
                //第0个是数据类型
                const jsonData = data.slice(1);
                fs.writeFileSync(path + `${sheetName}.json`, JSON.stringify(jsonData, null, '\t'))
                resolve(0)
            }
            catch (error) {
                reject(error)
            }
        })
    }

    saveToTs(path: string, sheetName: string, data: any[]) {
        return new Promise((resolve, reject) => {
            try {
                //第0个是数据类型
                const typeObj = data[0]
                //实际数据
                const jsonData = data.slice(1);

                // 设置类
                let tsString = `export class ${sheetName} {\n`;
                for (let key in typeObj) {
                    tsString += `\t${key}?: ${typeObj[key]};\n`;
                }
                tsString += `}\n\n`;

                // 设置数据
                tsString += `export const ${sheetName}_configs: ${sheetName}[] = [\n`
                for (let i = 0; i < jsonData.length; i++) {
                    tsString += '\t{\n';
                    for (let key in jsonData[i]) {
                        tsString += `\t\t${key}: `;
                        if (typeObj[key] == 'string') {
                            tsString += `'${jsonData[i][key]}'`
                        }
                        else if (typeObj[key] == 'number') {
                            tsString += Number(jsonData[i][key])
                        }
                        else if (typeObj[key] == 'number[]') {
                            const v = jsonData[i][key] + ''
                            const arrV: any[] = v.split(',')
                            tsString += '[';
                            for (let j = 0; j < arrV.length; j++) {
                                tsString += Number(arrV[j])
                                if (j < arrV.length - 1) {
                                    tsString += ', '
                                }
                            }
                            tsString += ']';
                        }
                        tsString += ',\n'
                    }
                    tsString += '\t},\n'
                }
                tsString += '];\n'

                fs.writeFileSync(path + `${sheetName}.ts`, tsString)

                resolve(tsString)
            }
            catch (error) {
                reject(error)
            }
        })
    }
}

console.log('*********excelTools start')

const excelTools = new ExcelTools();
excelTools.parse()